import { createApp } from "vue";
import type { App as Root } from "vue";
import { createWebHistory, createRouter } from "vue-router";
import isInIcestark from "@ice/stark-app/lib/isInIcestark";
import getBasename from "@ice/stark-app/lib/getBasename";
import setLibraryName from '@ice/stark-app/lib/setLibraryName';
import App from "./App.vue";
import routes from "./routes";

// @ts-ignore
import api from "./request/api.js";
// @ts-ignore
import http from "./request/index.js";
// @ts-ignore
import { setIsInMainApp } from "./config/index.js";
// 导出
// @ts-ignore
import { delUndefined } from "./util/index";
// @ts-ignore
import exportExcel from "./util/exportExcel"; //excel导出
import lodash from "lodash";
// @ts-ignore
import { addRoutes, asyncRoutes } from "./config/asyncRouter.js";
// element-plus
import ElementPlus from "element-plus";
import "element-plus/dist/index.css";
// element-plus/icons-vue
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
// css
import "./css/index.css";

let vue: Root<Element> | null = null;

setLibraryName('resource');

const runApp = (container: Element | string) => {
  const history = createWebHistory(isInIcestark() ? getBasename() : "/");
  const router = createRouter({
    base: getBasename(),
    history,
    routes,
  });
  // addRoutes(asyncRoutes).forEach((item) => {//添加动态路由
  //   router.addRoute(item);
  // });
  vue = createApp(App);
  vue.config.globalProperties.$api = api;
  vue.config.globalProperties.$http = http;
  vue.config.globalProperties.$exportExcel = exportExcel;
  vue.config.globalProperties.$lodash = lodash;
  vue.config.globalProperties.$delUndefined = delUndefined;

  // 全局注册图标
  for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    vue.component(key, component)
  }

  vue.use(ElementPlus, { size: 'small'});
  vue.use(router);
  vue.mount(container);
};
if (!isInIcestark()) {
  setIsInMainApp(true);
  runApp("#app");
}

export function mount({ container }: { container: Element }) {
  setIsInMainApp(false);
  runApp(container);
}

export function unmount() {
  if (vue) {
    vue.unmount();
  }
}
